var productslistPage = avalon.define({
    $id: "productslistPage",
    layout: true,
    categorydata: [],
    categoryId: 0,
    subCategoryId: '',
    category: [],
    categorys: [],
    subCategory: [],
    // selected: '',
    fac: [],
    checked: '',
    productlist: {},
    // 原页面属性
    noProductData: "",
    checked: {},
    isChecked: function(value) {
        var checked = listPage.checked;
        if (null != checked[value]) {
            return true;
        } else {
            return false;
        }
    },
    data: {
        childs: [],
        isSmall: 0,
        categorys: [],
        parent: {
            name: ""
        },
        facets: []
    },

    getFacets: function() {
        mui.ajax('/category/getSearchCategory.json', {
            dataType: 'json',
            success: function(data) {
                console.log(data)
                productslistPage.category = data;
                setTimeout(() => {
                    productslistPage.getsubclass(data[0].id);
                }, 10)
            }
        });
    },
    chooseCategory: function(to) {
        // console.log(this, to)
        categoryId = to.target.value;
        sessionStorage.setItem('categoryId', to.target.value);
        document.getElementById('facetForm').reset();
        if (categoryId) {
            productslistPage.getsubclass(categoryId);
        }
    },
    getsubclass: function(categoryId) {
        mui.ajax('/category/getSubCategory.json', {
            dataType: 'json',
            data: { categoryId: categoryId },
            success: function(data) {
                productslistPage.categorys = data;
                productslistPage.getclass(data[0].id)
                sessionStorage.setItem('cid', data[0].id)
            }
        })
    },
    chooseCategorys: function(to) {
        subCategoryId = to.target.value;
        sessionStorage.setItem('subCategoryId', to.target.value);
        if (subCategoryId) {
            productslistPage.getclass(subCategoryId)
            productslistPage.getproductlist()
        }
    },
    getclass: function(subCategoryId) {
        mui.ajax('/category/getSearchByCategory.json', {
            dataType: 'json',
            data: { categoryId: subCategoryId },
            success: function(data) {
                productslistPage.categorydata = data;
            }
        })
    },
    getproductlist: function() {
        var cid = sessionStorage.getItem('cid');
        var fac = [];
        mui.ajax('/product/search.json', {
            dataType: 'json',
            data: { cid: cid, facetIds: fac, page: 1, pageSize: 18 },
            success: function(data) {
                // console.log(data)
                productslistPage.productlist = data;
            }
        })
    },
    compare: { //比较
        btnText: "Product Comparison",
        values: [],
        max: 9,
        selected: function(id) {
            var icheckbox = $('#' + id);
            if ($(".compareBtn").hasClass("compared")) {
                var max = this.max;
                var values = this.values;
                if (icheckbox.is(':checked')) {
                    if (values.length + 1 > max) {
                        $(icheckbox).attr("checked", false);
                        mui.toast("You can choose " + max + " products at most");
                    } else {
                        values.push(id);
                        this.btnText = "Complete(" + values.length + "/" + max + ")";
                        this.values = values;
                    }

                } else {
                    var tmpValues = [];
                    avalon.each(values, function(i, value) {
                        if (id != value) {
                            tmpValues.push(value);
                        }
                    });
                    this.values = tmpValues;
                    this.btnText = "Complete(" + tmpValues.length + "/" + max + ")";
                }
            } else {
                $(icheckbox).attr("checked", false);
                var url = "pdp.html?id=" + id;
                mui.openWindow({
                    url: url
                });
            }

        }
    }
});
mui.ready(function() {
    productslistPage.getFacets();
    productslistPage.getproductlist();
    mui.init({
        pullRefresh: {
            container: "#productslist", //下拉刷新容器标识，querySelector能定位的css选择器均可，比如：id、.class等
            down: {
                auto: true,
                contentdown: $.i18n.contentDown,
                contentover: $.i18n.contentOver,
                contentrefresh: $.i18n.contentRefresh,
                callback: () => { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
                    var cid = sessionStorage.getItem('cid');
                    var fac = [];
                    mui.ajax('/product/search.json', {
                        dataType: 'json',
                        data: { cid: cid, facetIds: fac, page: 1, pageSize: 18 },
                        success: (data) => {
                            productslistPage.productlist = data;
                            console.log(data)
                        }
                    })
                    mui('#productslist').pullRefresh().endPulldown(true);
                }
            },
            up: {
                height: 50, //可选.默认50.触发上拉加载拖动距离
                auto: true, //可选,默认false.自动上拉加载一次
                contentrefresh: "正在加载...", //可选，正在加载状态时，上拉加载控件上显示的标题内容
                contentnomore: '没有更多数据了', //可选，请求完毕若没有更多数据时显示的提醒内容；
                callback: () => { //必选，刷新函数，根据具体业务来编写，比如通过ajax从服务器获取新数据；
                    mui.ajax('/product/search.json', {
                        dataType: 'json',
                        data: {},
                        success: () => {

                        }
                    })
                    this.endPullupToRefresh(true | false);
                }
            }
        }
    })
    mui('body').on('tap', 'a', function() { document.location.href = this.href; }); //解决页面中的a不能跳转
    var btn = document.getElementById("submit"); // Filter按钮
    //监听filter点击事件
    btn.addEventListener("tap", function() {
        mui('.mui-off-canvas-wrap').offCanvas('show');
    });
    //触发submit按钮的点击事件
    mui.trigger(btn, 'tap');
    window.onload = function() {
            mui('#offCanvasSideScroll').scroll();
            mui('#offCanvasContentScroll').scroll();
        }
        // YES按钮
    $('.yesBtn').on('tap', function(e) {
        mui('.mui-off-canvas-wrap').offCanvas('close');
    });
    // reset搜索条件
    $('.resetBtn').on('tap', function(e) {
            console.log(this, e)
        })
        //layout布局
    mui(".mui-bar-nav").on('tap', '.layout', function() {
        var layout = productslistPage.layout;
        if (layout) {
            productslistPage.layout = false;
        } else {
            productslistPage.layout = true;
        }
    });
    //点击开始比较按钮
    mui(".filter-bar").on('tap', '.startCompare', function() {
        productslistPage.compare.btnText = "Complete";

        //隐藏不需要比较的类目
        if (1 == productslistPage.data.isSmall) {
            $(".catItems").addClass("mui-hidden");
            avalon.each(productslistPage.data.categorys, function(i, category) {
                $("#" + category.id).removeClass("mui-hidden");
            });
        }
        if ($(".icheckbox").hasClass("mui-hidden")) {
            $(".icheckbox").removeClass("mui-hidden");
        }
        if (!$(".product").hasClass("mui-checkbox")) {
            $(".product").addClass("mui-checkbox");
        }

        if (!$(".compareBtn").hasClass("compared")) {
            $(".compareBtn").addClass("compared");
        }
        if ($(".compareBtn").hasClass("startCompare")) {
            $(".compareBtn").removeClass("startCompare");
        }
    });

    //跳转到比较页面
    mui(".filter-bar").on('tap', '.compared', function() {
        var values = productslistPage.compare.values;
        if (values.length == 0) {
            productslistPage.compare.btnText = "Product Comparison";
            $(".icheckbox").addClass("mui-hidden");
            $(".compareBtn").addClass("startCompare");
            $(".compareBtn").removeClass("compared");
            if (1 == productslistPage.data.isSmall) {
                $(".catItems").removeClass("mui-hidden");
            }

        } else if (values.length == 1) {
            mui.toast('Select two products at least');
        } else {
            var url = "compare.html";
            mui.openWindow({
                url: url + "?id=" + values
            });
        }
    });
})